// 存储与用户相关的信息
import { createSlice } from "@reduxjs/toolkit"
import { setToken as _setToken,getToken,removeToken } from "@/utils"
import { loginAPI,userInfoAPI } from "@/apis/user"
const userStore = createSlice({
  name:'user',
  initialState:{
    token:getToken() || '',
    userInfo:{}
  },
  reducers:{
    // 1、获取token并进行存储
    setToken(state,action) {
      state.token = action.payload
      // 将token持久化存储到本地
      _setToken(action.payload)
    },
    // 2、获取用户信息并进行存储
    setUserInfo(state,action) {
      state.userInfo = action.payload
    },

    // 3、退出登录，清空token以及用户信息
    loginOut(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

const {setToken,setUserInfo,loginOut} = userStore.actions
// 1、封装登录的异步请求，获取token并进行存储
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.data.token))
    // console.log(res)
  }
}
// 2、封装异步请求，获取用户信息并进行存储
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await userInfoAPI()
    dispatch(setUserInfo(res.data.data))
  }
}

export {setToken,fetchLogin,fetchUserInfo,loginOut}

const userReducer = userStore.reducer
export default userReducer